<?php

class Bug extends MY_Controller
{	
	private $user_id = null;
	
	function Bug()
	{
		parent::MY_Controller();

		header('Expires: Thu, 01-Jan-70 00:00:01 GMT');
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Pragma: no-cache');
		
		$this->user_id = (int)$this->session->userdata('user_id');
		if(!$this->user_id) redirect( site_url('/', 'location') );
		
		# add custom css file for user controller
		$this->data['header_data']['css'][] = '/css/home.css';
		$this->data['header_data']['js'][] = '/js/tmp.js';
		
		$this->lang->load('bug');

		# default title in case controller does not specify particular title
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('submit_bug');
	}
	
	public function submit()
	{
		$this->load->library('form_validation');
		
		if($this->input->post('submit'))
		{
			# anti robot/automaton checker
			if( (int)$this->input->post('tmp') < 5 )
			{
				redirect( site_url('bug/submit'), 'location' );
				die;
			}
			
			// first check if the nonce is correct
			$nonce = $this->input->xss_clean($this->input->post('nonce'));
			if($nonce !== $this->session->userdata('bug_nonce'))
			{
				$this->load->helper('cookie');
				if( !get_cookie('tt.me') ) 
				{
					redirect( site_url('service/cookies'), 'location' );	
				}
				else
				{					
					redirect( site_url('bug/submit'), 'location' );	
				}
				die;
			}

			$bugtype = (int)$this->input->post('bugtype');
			$bugtext = $this->input->xss_clean( $this->input->post('bug_description') );
			$bugtext = trim($bugtext);
			
			$this->load->model('Bug_model', 'bug');
			
			if( !empty($bugtext) && strlen($bugtext) > 20 )  
			{
				$this->bug->save($this->user_id, $bugtype, $bugtext);
			}
			
			redirect( site_url('bug/status/ok'), 'location' );
			die;
		}
		else
		{
			$nonce = md5(uniqid(rand(), false));	
			$this->session->set_userdata('bug_nonce', $nonce);
			$viewdata['nonce'] = $nonce;
			$this->data['content'] = $this->load->view('bug/submit', $viewdata, true);
		}
		
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);		
	}
	
	
	public function status($code)
	{
		switch($code)
		{
			/*
			case 'ok':
				$viewdata['message'] = lang('bug_saved');
				$this->data['content'] = $this->load->view('bug/status', $viewdata, true);
				break;
			*/
				
			default:
				$viewdata['message'] = lang('bug_saved');
				$this->data['content'] = $this->load->view('bug/status', $viewdata, true);
				break;
		}
		$this->data['no_sidebar'] = true;
		$this->load->view('global/master-view', $this->data);	
	}
}
